package main

import (
	"flag"
	"log"
	"reflect"
	"encoding/json"
	graphc "code.google.com/p/feedgraph/graph/http"
	graph "code.google.com/p/feedgraph/graph"
	"github.com/alexjlockwood/gcm"
)

var g graphc.Proxy

type watcher struct {
	node string
	regId string
}

type message struct {
	JSONString string
}

var watchers = make(map[watcher]bool)

func edgeHandler(sub graph.Edge) {

	obj := sub.Object.(map[string]interface{})
	regId := obj["AndroidRegId"]
	

	if sub.Relation == "" || regId == nil || reflect.ValueOf(regId).Kind() != reflect.String {
		return
	}

	w := watcher{sub.Relation, regId.(string)}

	ok := watchers[w]

	if !ok {
		watchers[w] = true
		f := func (e graph.Edge) {

			log.Println("sending msg to ", w.regId)

			payload, err := json.Marshal(e)

			if err != nil {
				log.Println(err)
				return
			}

			msg := gcm.NewMessage(message{string(payload)}, w.regId)
			resp, err := gcm.SendNoRetry(msg)

			log.Println(resp, err)
		}

		log.Println("started watching:", w)
		go g.Watch(w.node, "*", 0, f)
	} else {
		log.Println("re-registered:",  w)
	}
}

func main () {

	gid := flag.String("graph", "test", "graph to watch")

	flag.Parse()

	g = graphc.Graph(*gid)

	g.Watch("subscriptions", "*", 0, graphc.EdgeHandler (edgeHandler))
}

